//
//  KLReceiveBrunchTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 17/2/22.
//  Copyright © 2017年 陈宾鹏. All rights reserved.
//

#import "KLReceiveBrunchTableViewController.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "HemaFunction.h"
#import "Masonry.h"
#import "KLTranspondBrunchVC.h"

@interface KLReceiveBrunchTableViewController ()
@property(nonatomic,strong)NSArray *groupList;
@end

@implementation KLReceiveBrunchTableViewController
-(NSArray *)groupList{
    if(!_groupList){
        _groupList = [NSArray array];
    }
    return _groupList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"收到的钥匙串";
    self.tableView.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    //对tablevie的设置
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, -40, 0, 0);
    //设置导航栏返回按钮
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    
    [self refreshReceivedBrunchKeys];
}-(void)doBack:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.groupList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *groupDic = self.groupList[section];
    NSArray *children = [groupDic objectForKey:@"children"];
    if(children == nil)
        return 0;
    else
        return children.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"receiveBrunch"];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"receiveBrunch"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSDictionary *groupDic_src = self.groupList[indexPath.section];
    NSArray *children = [groupDic_src objectForKey:@"children"];
    if(children == nil){
        return cell;
    }
    NSDictionary *groupDic = children[indexPath.row];
    NSString *valid_type = [groupDic objectForKey:@"valid_type"];
    if(valid_type.integerValue == 1){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"未生效";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(238, 230, 133);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if(valid_type.integerValue == 2){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"已过期";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(240, 101, 101);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if (valid_type.integerValue == 4){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"可使用";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(0, 205, 102);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if (valid_type.integerValue == 3){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"永久有效";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(0, 205, 102);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }
    
    NSString *groupright = [groupDic objectForKey:@"groupright"];//0不可转发，1可转发，2二级串主，3模板创建人
    UILabel *nameLabel = [[UILabel alloc]init];
    switch (groupright.integerValue) {
        case 0:
            nameLabel.text = @"不可转发钥匙串";
            break;
        case 1:
            nameLabel.text = @"可转发钥匙串";
            break;
        case 2:
            nameLabel.text = @"二级钥匙串主";
            break;
        case 3:
            nameLabel.text = @"一级钥匙串主";
            break;
        default:
            break;
    }
    nameLabel.textAlignment = NSTextAlignmentRight;
    nameLabel.textColor = [UIColor darkGrayColor];
    nameLabel.alpha = 0.8;
    nameLabel.font = [UIFont systemFontOfSize:15];
    nameLabel.numberOfLines = 1;
    nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    [cell.contentView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.height.mas_equalTo(25);
        make.left.mas_equalTo(45);
    }];
    
    UILabel *timeLabel = [[UILabel alloc]init];
    timeLabel.textColor = [UIColor lightGrayColor];
    timeLabel.alpha = 0.8;
    timeLabel.font = [UIFont systemFontOfSize:13];
    NSString *starTime = [groupDic objectForKey:@"begin_time"];
    starTime = [starTime substringToIndex:16];
    NSString *endTime = [groupDic objectForKey:@"end_time"];
    endTime = [endTime substringToIndex:16];
    timeLabel.text = [NSString stringWithFormat:@"有效期:%@至%@",starTime,endTime];
    
    [cell.contentView addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell).with.offset(30);
        make.height.mas_equalTo(25);
        make.left.equalTo(cell).with.offset(45);
    }];
    
    UILabel *phoneLabel = [[UILabel alloc]init];
    phoneLabel.textColor = [UIColor lightGrayColor];
    phoneLabel.alpha = 0.8;
    phoneLabel.font = [UIFont systemFontOfSize:13];
    phoneLabel.text = [NSString stringWithFormat:@"来自于用户:%@ （%@）",[groupDic objectForKey:@"recevier_phone"],[groupDic objectForKey:@"recevier_username"]];
    [cell.contentView addSubview:phoneLabel];
    [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell).with.offset(50);
        make.height.mas_equalTo(25);
        make.left.equalTo(cell).with.offset(45);
    }];
    
    if(indexPath.row == children.count-1){
        UIImageView *imageLine = [[UIImageView alloc]initWithFrame:CGRectMake(0, 79, UI_View_Width, 1.5)];
        imageLine.image = [UIImage imageNamed:@"line.png"];
        [cell.contentView addSubview:imageLine];
    }
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(self.groupList.count == 0)
        return nil;
    NSDictionary *groupDic = self.groupList[section];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 45)];
    view.backgroundColor = [UIColor whiteColor];
    UIImageView *iv = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"钥匙-线"]];
    [view addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(30);
        make.centerY.equalTo(view);
    }];
    UILabel *groupName = [[UILabel alloc]init];
    groupName.font = [UIFont systemFontOfSize:13];
    groupName.text = [NSString stringWithFormat:@"组名:%@",[groupDic objectForKey:@"group_name"]];
    [view addSubview:groupName];
    [groupName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iv.mas_rightMargin).with.offset(20);
        make.top.mas_equalTo(7);
    }];
    UILabel *countNum = [[UILabel alloc]init];
    countNum.font = [UIFont systemFontOfSize:13];
    countNum.text = [NSString stringWithFormat:@"包含锁数量:%@把",[groupDic objectForKey:@"count"]];
    [view addSubview:countNum];
    [countNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iv.mas_rightMargin).with.offset(20);
        make.bottom.mas_equalTo(-7);
    }];
    
    //分割线
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 44, UI_View_Width, 0.3)];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    
    
    return view;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *keyDic = self.groupList[indexPath.row];
    NSString *keyType = [keyDic objectForKey:@"keyright"];
    UITableViewRowAction *action0 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"转发" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        // 收回左滑出现的按钮(退出编辑模式)
        tableView.editing = NO;
        if(keyType.integerValue == 1){
            KLTranspondBrunchVC *transpondBrunchVC = [[KLTranspondBrunchVC alloc]init];
            transpondBrunchVC.brunchDetailDic = [self.groupList[indexPath.row] copy];
            [self.navigationController pushViewController:transpondBrunchVC animated:YES];
        }else if (keyType.integerValue == 0){
            [KLHelp showTextHUDforView:self.view text:@"该钥匙串为不可转发钥匙"];
        }
    }];
    if(keyType.integerValue == 1){
        action0.backgroundColor = [UIColor greenColor];
    }else if (keyType.integerValue == 0){
        action0.backgroundColor = [UIColor grayColor];
    }
    
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"删除%zd",indexPath.row);
        tableView.editing = NO;
    }];
    action1.backgroundColor = [UIColor redColor];
    return @[action0,action1];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45;
}

#pragma mark - 刷新收到的钥匙串
-(void)refreshReceivedBrunchKeys{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI getReceiveGroupBrunchListWithCompletionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"收到的钥匙串:%@",operation.responseString);
        NSDictionary *dic = operation.responseJSON;
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.groupList = [dic objectForKey:@"infor"];
            [self.tableView reloadData];
            if(self.groupList.count == 0){
                [KLHelp setNoDateImageWithView:self.view type:0];
            }else{
                [KLHelp removeImgViewAndNoticeLabel];
            }
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:error];
    }];
}
@end
